<?php

namespace App\Admin\Charts;

use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\ApexCharts\Chart;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderBar extends Chart
{

    public function __construct($containerSelector = null, $options = [])
    {
        parent::__construct($containerSelector, $options);

        $this->setUpOptions();
    }

    /**
     * 初始化图表配置
     */
    protected function setUpOptions()
    {
        $color = Admin::color();

        $colors = [$color->primary(), $color->primaryDarker()];

        $this->options([
            'colors' => $colors,
            'chart' => [
                'type' => 'line',
                'height' => 430
            ],
            'dataLabels' => [
                'enabled' => false,
                'offsetX' => -6,
                'style' => [
                    'fontSize' => '12px',
                    'colors' => ['#fff']
                ]
            ],
            'xaxis' => [
                'categories' => [],
            ],
        ]);
    }


    /**
     * 处理请求
     *
     * @param Request $request
     *
     * @return mixed|void
     */
    public function handle(Request $request)
    {

        $option = $request->get('option',7);
        $charts = DB::select("select date_format(order_time,'%Y-%m-%d') as day,count(id) as count from `orders` where date(order_time)>=date_sub(curdate(),interval {$option} day)  and status in (2,3,4)  group by day order by day asc");
        $result = $this->category($charts,$option);
        $this->withCategories($result['category']);
        $this->withData($result['data']);

    }

    /**
     * 设置图表数据
     *
     * @param array $data
     *
     * @return $this
     */
    public function withData(array $data)
    {
        return $this->option('series', $data);
    }

    /**
     * 设置图表类别.
     *
     * @param array $data
     *
     * @return $this
     */
    public function withCategories(array $data)
    {
        return $this->option('xaxis.categories', $data);
    }

    public function category($categories,$option)
    {
        $arr = [];
        foreach ($categories as $v){
            $arr[$v->day]= $v->count;
        }

        $current_date = date('Y-m-d');
        $category = [];
        $data = [];
        for ($i=0;$i<$option;$i++){
            $day = date('Y-m-d',strtotime($current_date. "-$i day"));
            if (isset($arr[$day])){
                $data[$i] = $arr[$day];
            }else{
                $data[$i] = 0;
            }

            $category[$i] = $day;
        }

        return ['category' => $category,'data' => [['name'=> '新增数','data' => $data]]];
    }


    /**
     * 这里覆写父类的方法，不再查询数据
     */
    protected function buildData()
    {
    }

    /**
     * 渲染图表
     *
     * @return string
     */
    public function render()
    {
        $this->buildData();

        return parent::render();
    }

}
